# -*- coding:utf-8 -*-
from tornado import gen
import StringIO
import xlwt

from appcommon.framework import WebBaseHandler
from common import utiltool
import models as tikum
from common import timetool
import os
import settings


class TikuListHandler(WebBaseHandler):
    """
    题库列表
    """
    @gen.coroutine
    def get(self):
        sort = self.get_argument('sort', 'id')
        rows = self.get_argument('rows', '20')
        page = self.get_argument('page', '1')
        order = self.get_argument('order', 'asc')
        car_type = self.get_argument('car_type', '')
        exam_type = self.get_argument('exam_type', '')
        keyword = self.get_argument('keyword', '')
        vip = self.get_argument('vip', '')
        tiku_list = yield tikum.get_tiku_list(sort, rows, page, order, car_type, exam_type, vip, keyword)
        for item in tiku_list[0]:
            item['pubtime'] = timetool.convert_timestamp_to_date(item['pubtime'])
        res = dict(
            total=tiku_list[1],
            rows=tiku_list[0]
        )
        utiltool.response_write(self, res)


class DeleteTikuHandler(WebBaseHandler):
    """
    删除题目
    """
    @gen.coroutine
    def post(self):
        sub_id = self.get_argument('sub_id', '0')
        try:
            yield tikum.del_tiku(sub_id)
            res = {'code': '0', 'msg': u'保存成功'}
        except Exception, e:
            res = {'code': '1', 'msg': u'删除失败'}
        utiltool.response_write(self, res)



class UpdateTikuHandler(WebBaseHandler):
    """
    更新题目
    """
    @gen.coroutine
    def post(self):
        dic = self.request.arguments
        for k in dic.iterkeys():
            dic[k] = dic[k][0]
        # try:
        #     yield tikum.update_tiku(dic)
        #     res = {'code': '0', 'msg': u'保存成功'}
        # except Exception, e:
        #     res = {'code': '1', 'msg': u'保存失败'}

        yield tikum.update_tiku(dic)
        res = {'code': '0', 'msg': u'保存成功'}
        utiltool.response_write(self, res)



class UpdateVIPidHandler(WebBaseHandler):
    """
    更新题目
    """
    @gen.coroutine
    def post(self):
        sub_id = self.get_argument('sub_id', '0')
        vip_id = int(self.get_argument('vip_id', '0'))
        exam_type = self.get_argument('exam_type', '1')
        # vip_info = yield tikum.get_vip_info_with_sub_id(sub_id)
        # if vip_info['vip_id'] == vip_id:
        #     res = {'code': '0', 'msg': u'保存成功'}
        # elif vip_id > vip_info['vip_id']:
        #     yield tikum.update_vip_id_2_big(vip_info['vip_id'], vip_id, vip_info['vip'], exam_type)
        #     yield tikum.update_vip_id(sub_id, vip_id, exam_type)
        #     res = {'code': '0', 'msg': u'保存成功'}
        # else:
        #     yield tikum.update_vip_id_2_small(vip_info['vip_id'], vip_id, vip_info['vip'], exam_type)
        #     yield tikum.update_vip_id(sub_id, vip_id, exam_type)
        #     res = {'code': '0', 'msg': u'保存成功'}
        yield tikum.update_vip_id(sub_id, vip_id, exam_type)
        res = {'code': '0', 'msg': u'保存成功'}
        utiltool.response_write(self, res)


class UpdateTikuSortHandler(WebBaseHandler):
    """
    更新题目排序ID
    """
    @gen.coroutine
    def post(self):
        sub_id = self.get_argument('sub_id', '0')
        order_id = int(self.get_argument('order_id', '0'))
        # sub_info = yield tikum.get_sub_info_with_sub_id(sub_id)
        # if sub_info['order_id'] == order_id:
        #     res = {'code': '0', 'msg': u'保存成功'}
        # elif order_id > sub_info['order_id']:
        #     yield tikum.update_sort_id_2_big(sub_info['order_id'], order_id)
        #     yield tikum.update_sort_id(sub_id, order_id)
        #     res = {'code': '0', 'msg': u'保存成功'}
        # else:
        #     yield tikum.update_sort_id_2_small(sub_info['order_id'], order_id)
        #     yield tikum.update_sort_id(sub_id, order_id)
        #     res = {'code': '0', 'msg': u'保存成功'}
        yield tikum.update_sort_id(sub_id, order_id)
        res = {'code': '0', 'msg': u'保存成功'}
        utiltool.response_write(self, res)


class GetMediaListHandler(WebBaseHandler):
    """
    获取题库的图片或语音文件列表
    """
    @gen.coroutine
    def get(self):
        # 0：题库图片
        # 1：解析图片
        # 2：解析语音
        # 3：视频
        rows = self.get_argument('rows', '20')
        page = self.get_argument('page', '1')
        type = self.get_argument('type', '0')
        file_name = self.get_argument('file_name', '')
        info = yield tikum.get_media_list(type, file_name)
        start = (int(page) - 1) * int(rows)
        res = {"rows": info[start:start + int(rows)], "total": len(info)}
        utiltool.response_write(self, res)


class DelMediaHandler(WebBaseHandler):
    """
    """
    @gen.coroutine
    def post(self):
        # 0：题库图片
        # 1：解析图片
        # 2：解析语音
        # 3：视频
        id = self.get_argument('id', '0')
        media_info = yield tikum.get_media_with_id(id)
        if media_info['type'] == 0:
            upload_path = settings.IMG_BASE_PATH + 'tiku/'
        elif media_info['type'] == 1:
            upload_path = settings.IMG_BASE_PATH + 'analysis/'
        elif media_info['type'] == 2:
            upload_path = u'/usr/share/nginx/static/audio/'
        else:
            upload_path = settings.IMG_BASE_PATH + 'vippic/'

        file_path = upload_path + media_info['file_name']
        os.remove(file_path)
        yield tikum.del_media_with_id(id)
        res = {"code": "0", "msg": u"删除成功"}
        utiltool.response_write(self, res)


class AddMediaHandler(WebBaseHandler):
    """
    """
    @gen.coroutine
    def post(self):
        # 0：题库图片
        # 1：解析图片
        # 2：解析语音
        # 3：视频
        file_metas = self.request.files['file']
        type = self.get_argument('type', '0')
        if type == '0':
            upload_path = settings.IMG_BASE_PATH + 'tiku/'
        elif type == '1':
            upload_path = settings.IMG_BASE_PATH + 'analysis/'
        elif type == '2':
            upload_path = u'/usr/share/nginx/static/audio/'
        else:
            upload_path = settings.IMG_BASE_PATH + 'vippic/'
        for meta in file_metas:
            os.path.exists('upload_path')
            filename = meta['filename']
            filepath = os.path.join(upload_path, filename)
            print filepath
            with open(filepath, 'wb') as up:  # 有些文件需要已二进制的形式存储，实际中可以更改
                up.write(meta['body'])
            yield tikum.add_media_2_mysql(filename, type)
        res = {"code": "0", "msg": u"添加成功"}
        utiltool.response_write(self, res)


class MediaToMysqlHandler(WebBaseHandler):
    """
    获取题库的图片或语音文件列表
    """
    @gen.coroutine
    def get(self):
        # 0：题库图片
        # 1：解析图片
        # 2：解析语音
        # 3：视频
        type = self.get_argument('type', '0')
        if type == '0':
            file_path = u'/usr/share/nginx/static/img/tiku'
        elif type == '1':
            file_path = u'/usr/share/nginx/static/img/analysis'
        elif type == '2':
            file_path = u'/usr/share/nginx/static/audio'
        else:
            file_path = u'/usr/share/nginx/static/video'
        yield tikum.delete_media_from_mysql(type)
        file_list = os.listdir(file_path)
        for file in file_list:
            yield tikum.add_media_2_mysql(file, type)
        utiltool.response_write(self, {"code": "0"})



class GetVideoListHandler(WebBaseHandler):
    """
    获取题库的图片或语音文件列表
    """

    @gen.coroutine
    def get(self):
        rows = self.get_argument('rows', '20')
        page = self.get_argument('page', '1')
        file_name = self.get_argument('file_name', '')
        info = yield tikum.get_video_list(file_name)
        start = (int(page) - 1) * int(rows)
        res = {"rows": info[start:start + int(rows)], "total": len(info)}
        utiltool.response_write(self, res)


class DelVideoHandler(WebBaseHandler):
    """
    获取题库的图片或语音文件列表
    """

    @gen.coroutine
    def post(self):
        id = self.get_argument('id', '0')
        video_info = yield tikum.get_video_with_id(id)
        pic_path = settings.IMG_BASE_PATH + 'videopic/'
        video_path = u'/usr/share/nginx/static/video/'

        pic_file = pic_path + video_info['pic']
        video_file = video_path + video_info['file_name']
        if os.path.exists(pic_file):
            os.remove(pic_file)
        if os.path.exists(pic_file):
            os.remove(video_file)

        yield tikum.del_video_with_id(id)
        res = {"code": "0", "msg": u"删除成功"}
        utiltool.response_write(self, res)


class AddVideoHandler(WebBaseHandler):
    """
    获取题库的图片或语音文件列表
    """
    @gen.coroutine
    def post(self):
        title = self.get_argument('title', '')
        content = self.get_argument('content', '')
        type = self.get_argument('type', '0')
        car_type = self.get_argument('car_type', '0')
        if 'file_name' in self.request.files.keys():
            video_meta = self.request.files['file_name']
        else:
            video_meta = []
        if 'pic' in self.request.files.keys():
            pic_meta = self.request.files['pic']
        else:
            pic_meta = []
        pic_path = settings.IMG_BASE_PATH + 'videopic/'
        video_path = u'/usr/share/nginx/static/video/'
        video_name = ""
        pic_name = ""
        for meta in video_meta:
            video_name = meta['filename']
            video_path = os.path.join(video_path, video_name)
            with open(video_path, 'wb') as up:  # 有些文件需要已二进制的形式存储，实际中可以更改
                up.write(meta['body'])
        for meta in pic_meta:
            pic_name = meta['filename']
            pic_path = os.path.join(pic_path, pic_name)
            with open(pic_path, 'wb') as up:  # 有些文件需要已二进制的形式存储，实际中可以更改
                up.write(meta['body'])
        yield tikum.add_video_2_mysql(video_name, pic_name, title, content, type,car_type)
        res = {"code": "0", "msg": u"添加成功"}
        utiltool.response_write(self, res)


class UpdateVideoHandler(WebBaseHandler):
    """
    获取题库的图片或语音文件列表
    """
    @gen.coroutine
    def post(self):
        id = self.get_argument('id', '')
        title = self.get_argument('title', '')
        content = self.get_argument('content', '')
        type = self.get_argument('type', '0')
        car_type = self.get_argument('car_type', '0')
        if 'pic_name' in self.request.files.keys():
            pic_meta = self.request.files['pic_name']
        else:
            pic_meta = []
        pic_path = settings.IMG_BASE_PATH + 'videopic/'
        pic_name = ""
        for meta in pic_meta:
            pic_name = meta['filename']
            pic_path = os.path.join(pic_path, pic_name)
            with open(pic_path, 'wb') as up:  # 有些文件需要已二进制的形式存储，实际中可以更改
                up.write(meta['body'])
        yield tikum.update_video_info(id, title, content, type, car_type, pic_name)
        res = {"code": "0", "msg": u"添加成功"}
        utiltool.response_write(self, res)


class ExportTikuHandler(WebBaseHandler):
    """导出题库
    """
    @gen.coroutine
    def get(self):
        info = yield tikum.get_all_tiku()
        s = StringIO.StringIO()
        f = xlwt.Workbook()  # 创建工作簿
        sheet1 = f.add_sheet(u'sheet1', cell_overwrite_ok=True)  # 创建sheet
        row0 = [u'题号', u'车型', u'科目', u'章节', u'VIP', u'VIP排序',
                u'题目', u'题目图片', u'选项A', u'选项B', u'选项C', u'选项D', u'答案',
                u'解析文字', u'解析图片', u'题目属性', u'题目类型',
                u'答题技巧', u'技巧语音', u'VIP解析图片',
                u'城市', u'排序ID', u'总答题数', u'错误数',
                u'星级']
        current_time = timetool.get_timestamp()
        # 生成第一行
        for i in range(0, len(row0)):
            sheet1.write(0, i, row0[i])
        for i in range(0, len(info)):
            sheet1.write(i + 1, 0, info[i]['sub_id'])
            sheet1.write(i + 1, 1, info[i]['car_type'])
            sheet1.write(i + 1, 2, info[i]['exam_type'])
            sheet1.write(i + 1, 3, info[i]['sub_chapte'])
            sheet1.write(i + 1, 4, info[i]['vip'])
            sheet1.write(i + 1, 5, info[i]['vip_id'])
            sheet1.write(i + 1, 6, info[i]['sub_title'])
            sheet1.write(i + 1, 7, info[i]['sub_pic'])
            sheet1.write(i + 1, 8, info[i]['a'])
            sheet1.write(i + 1, 9, info[i]['b'])
            sheet1.write(i + 1, 10, info[i]['c'])
            sheet1.write(i + 1, 11, info[i]['d'])
            sheet1.write(i + 1, 12, info[i]['answer'])
            sheet1.write(i + 1, 13, info[i]['sub_infos'])
            sheet1.write(i + 1, 14, info[i]['info_pic'])
            sheet1.write(i + 1, 15, info[i]['sub_class'])
            if info[i]['sub_type'] == '1':
                sub_type = u'判断'
            elif info[i]['sub_type'] == '2':
                sub_type = u'选择'
            else:
                sub_type = info[i]['sub_type']
            sheet1.write(i + 1, 16, sub_type)
            sheet1.write(i + 1, 17, info[i]['dtjq'])
            sheet1.write(i + 1, 18, info[i]['jqyy'])
            sheet1.write(i + 1, 19, info[i]['vip_pic'])
            sheet1.write(i + 1, 20, info[i]['city'])
            sheet1.write(i + 1, 21, info[i]['order_id'])
            sheet1.write(i + 1, 22, info[i]['total_cnt'])
            sheet1.write(i + 1, 23, info[i]['err_cnt'])
            sheet1.write(i + 1, 24, info[i]['stars'])
        f.save(s)  # 保存文件
        s.seek(0)

        filename = u"题库.xls"
        self.set_header('Content-Type', 'application/octet-stream')
        self.set_header('Content-Disposition', 'attachment; filename=' + filename)
        buf_size = 4096
        while True:
            data = s.read(buf_size)
            if not data:
                break
            self.write(data)
        self.finish()